package com.eqdd.yiqidian.ui.companyspace

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector
import com.eqdd.yiqidian.base.AppConstent
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.LeaveMessageBean
import com.eqdd.yiqidian.box.ItemDecoration.SectionDividerItemDecoration
import com.eqdd.yiqidian.box.span.NoLineClickSpan
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.kotlin.BaseRecyclerViewAdapter
import com.eqdd.yiqidian.kotlin.toArrayList
import com.eqdd.yiqidian.ui.InputDialogActivity
import com.eqdd.yiqidian.ui.mine.UserCardActivity
import com.eqdd.yiqidian.utils.DensityUtil
import com.eqdd.yiqidian.utils.ImageUtil
import com.eqdd.yiqidian.utils.TimeUtil
import com.eqdd.yiqidian.utils.ToastUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_leave_message_info.*
import kotlinx.android.synthetic.main.list_item_138.view.*
import kotlinx.android.synthetic.main.list_item_78.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.util.*

/**
 * Created by jhj on 18-7-2.
 */
class LeaveMessageInfoActivity : BaseActivity() {
    private var messageBean: LeaveMessageBean? = null
    private var clickMessageBean: LeaveMessageBean? = null
    private var clickPosition = -1
    private var isMyMessage: Boolean = false

    override fun initBinding() {
        setContentView(R.layout.activity_leave_message_info)
        initTopTitleBar(View.VISIBLE, "留言")
    }

    private var id: Int = -1

    override fun initData() {
        id = intent.getIntExtra(Config.ID, -1)
        if (id == -1) {
            toast("获取留言失败")
            finish()
            return
        }
        refreshData()
    }

    fun refreshData() {
        OkGo.post<HttpResult<LeaveMessageBean>>(HttpConfig.BASE_URL + HttpConfig.LEAVE_MESSAGE_INFO)
                .params("leavemsgId", id)
                .execute(object : DialogCallBack<HttpResult<LeaveMessageBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<LeaveMessageBean>>?) {
                        val result = response?.body()
                        if (result?.items != null) {
                            messageBean = result.items
                            setView()
                        }
                    }
                })
    }

    private var deleteType: Int = 0

    override fun setView() {
        messageBean?.let {
            ImageUtil.setCircleImage(it.iphoto, iv_head)
            stv_name.text = it.upname
            iv_option.visibility = View.GONE
            tv_depart.text = String.format(Locale.CHINA, "%s - %s", it.departName, it?.postName)
            tv_time.text = TimeUtil.formatWebTime(it.createTime)
            tv_message.text = it.message
            tv_message.onClick { view ->
                deleteType = 1
                isMyMessage = user.guid == it.creater
                clickMessageBean = it
                showMoreDialog()
            }
            recyclerView.layoutManager = LinearLayoutManager(this)
            val adapter = MessageAdapter()
            adapter.dataList = it.childList?.toArrayList() ?: arrayListOf<LeaveMessageBean>()
            recyclerView.adapter = adapter
        }
    }


    inner class MessageAdapter : BaseRecyclerViewAdapter<LeaveMessageBean>() {
        override fun onCreateView(viewType: Int): Int {
            return R.layout.list_item_157
        }

        override fun onBindViewItemViewHolder(holder: ItemViewHolder, bean: LeaveMessageBean, position: Int) {
            val spStr = SpannableString(bean.staffName + ":" + " @" + bean.parentStaffName + " " + bean.message)
            val firstSpan = NoLineClickSpan("#3423ff") { v ->
                startActivity<UserCardActivity>(Config.GUID to bean.creater)
            }
            val secondSpan = NoLineClickSpan("#3423ff", { v ->
                startActivity<UserCardActivity>(Config.GUID to bean.parentUserGuid)
            })
            spStr.setSpan(firstSpan, 0, bean.staffName.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
            val end = spStr.toString().indexOf("@") + 1 + (bean.parentStaffName?.length ?: 0)
            spStr.setSpan(secondSpan, spStr.toString().indexOf("@"), end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
            holder.itemView.tv_comment_comment.movementMethod = LinkMovementMethod.getInstance()
            holder.itemView.tv_comment_comment.text = spStr
            ItemClickSupport.addTo(recyclerView).setOnItemClickListener { recyclerView, position, v ->
                deleteType = 2
                isMyMessage = user.guid == bean.creater
                clickPosition = position
                clickMessageBean = bean
                showMoreDialog()
            }
        }
    }


    fun responseMessage(msg: String) {
        OkGo.post<HttpResult<LeaveMessageBean>>(HttpConfig.BASE_URL + HttpConfig.LEAVE_MESSAGE_ADD)
                .params("userGuid", user.guid)
                .params("userCompanyId", user.companyId)
                .params("message", msg)
                .params("companyId", clickMessageBean?.companyId ?: 0)
                .params("parentId", clickMessageBean?.id ?: 0)
                .params("parentUserGuid", clickMessageBean?.creater)
                .params("firstCommentId", id)
                .execute(object : DialogCallBack<HttpResult<LeaveMessageBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<LeaveMessageBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            refreshData()
                        } else {
                            toast(result?.msg ?: "")
                        }
                    }

                })
    }

    private fun showMoreDialog() {
        val objects = ArrayList<String>()
        objects.add("回复")
        objects.add("复制")
        objects.add("删除")
        val slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.list_item_54, object : SlimInjector<String> {
            override fun onInject(data: String?, injector: IViewInjector<out IViewInjector<*>>?) {
                injector?.text(R.id.tv_content, data)
            }
        }).updateData(objects as List<String>?)
        val moreDialog = MaterialDialog.Builder(this)
                .adapter(slimAdapterEx, LinearLayoutManager(this))
                .build()
        moreDialog.recyclerView.addItemDecoration(SectionDividerItemDecoration(this)
                .setHeadHeight(0)
                .setRightPadding(DensityUtil.percentW(40))
                .setLeftPadding(DensityUtil.percentW(40))
                .setLastBootomHeght(0))
        ItemClickSupport.addTo(moreDialog.getRecyclerView())
                .setOnItemClickListener { recyclerView, position, v ->
                    when (position) {
                        0 -> {
                            startActivityForResult<InputDialogActivity>(Config.INPUT, Config.TALK_TO to clickMessageBean?.upname)
                        }
                        1 -> {
                            val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                            // 将文本内容放到系统剪贴板里。
                            cm.primaryClip = ClipData.newPlainText("Lable", clickMessageBean?.message)
                            toast("已复制")
                        }
                        2 -> deleteComment() {
                            slimAdapterEx.getData().removeAt(clickPosition)
                            slimAdapterEx.notifyItemRemoved(clickPosition)
                        }
                    }
                    moreDialog.dismiss()
                }
        val slimAdapterExMore = moreDialog.recyclerView.adapter as SlimAdapterEx<String>
        if (isMyMessage && slimAdapterExMore.data.size == 2) {
            slimAdapterExMore.data.add("删除")
            slimAdapterExMore.notifyItemInserted(2)
        } else if (!isMyMessage && slimAdapterExMore.data.size == 3) {
            slimAdapterExMore.data.removeAt(2)
            slimAdapterExMore.notifyItemRemoved(2)
        }
        moreDialog.show()

    }

    private fun deleteComment(function: () -> Unit) {

        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.LEAVE_MESSAGE_DELETE)
                .params("userGuid", AppConstent.user.guid)
                .params("companyId", user.companyId)
                .params("msgId", clickMessageBean?.id ?: 0)
                .params("type", deleteType)
                .execute(object : DialogCallBack<HttpResult<*>>(this@LeaveMessageInfoActivity) {
                    override fun onSuccess(response: Response<HttpResult<*>>) {
                        val httpResult = response.body()
                        ToastUtil.showShort(httpResult.msg)
                        if (httpResult.status == 200) {
                            function()
                            refreshData()
                        }
                    }
                })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.SUCCESS) {
            when (requestCode) {
                Config.INPUT -> {
                    val str = data?.getStringExtra(Config.CONTENT)
                    responseMessage(str ?: "")
                }
            }
        }

    }

}